﻿using System.Drawing;
using System.IO;
using JustTest.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using System;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace JustTest.Account
{
    public partial class Register : Page
    {
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            string userName = this.UserName.Text;
            string firstName = this.FirstName.Text;
            string lastName = this.LastName.Text;


            var image = Image.FromFile(Server.MapPath(@"~\img\default-avatar.png"));
            byte[] currentUserImage = ImageToByteArray(image);

            var manager = new AuthenticationIdentityManager(new IdentityStore(new JustTestDb()));
            ApplicationUser u = new ApplicationUser { UserName = userName,FirstName = firstName, LastName = lastName, ProfilePicture = currentUserImage};
            IdentityResult result = manager.Users.CreateLocalUser(u, Password.Text);
            if (result.Success) 
            {
                manager.Authentication.SignIn(Context.GetOwinContext().Authentication, u.Id, isPersistent: false);
                OpenAuthProviders.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else 
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }

        protected byte[] ImageToByteArray(System.Drawing.Image img)
        {
            using (var ms = new MemoryStream())
            {
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                return ms.ToArray();
            }
        }
    }
}